<?php
declare (strict_types=1);

namespace app\user\service\user\admin;

use app\common\logic\payment\admin\PaymentOrderItem;
use app\common\service\BaseService;
use app\course\logic\base\admin\CourseStudent;
use app\course\logic\record\admin\LearnRecord;
use app\user\logic\user\admin\Account as AccountLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

/**
 * 用户账号-管理端接口
 */
class Account extends BaseService
{

    /**
     * @Inject()
     *
     * @var AccountLogic
     */
    protected $accountLogic;
    /**
     * @Inject()
     *
     * @var LearnRecord
     */
    protected $learnRecord;
    /**
     * @Inject()
     *
     * @var CourseStudent
     */
    protected $courseStudent;
    /**
     * @Inject()
     *
     * @var PaymentOrderItem
     */
    protected $paymentOrderItem;

    /**
     * 用户列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-15
     */
    public function index(): Response
    {
        // 搜索功能
        $map = [];
        Request::has('user_name', 'get', true) && $map[] = ['user_name|nick_name', 'like', '%' . Request::get('user_name/s') . '%'];
        Request::has('phone', 'get', true) && $map[] = ['phone', 'like', '%' . Request::get('phone/s') . '%'];
        Request::has('mhm_id', 'get', true) && $map[] = ['mhm_id', '=', Request::get('mhm_id/d')];
        if (Request::has('status', 'get', true) && Request::get('status/d', -1) !== -1) {
            $map[] = ['status', '=', Request::get('status/d')];
        }
        $data = $this->accountLogic->getUserList($map)->append(['status_text']);
        // 'balance','income','credit'
        // 定义字段
        $keyList = [
            'user'            => ListItem::make('custom')->title('基本信息')->width(100),
            'school_name'     => ListItem::make()->title('所属机构')->visible(request()->is_platform),
            // 'balance'         => ListItem::make()->title('余额'),
            // 'income'          => ListItem::make()->title('收入'),
            // 'credit'          => ListItem::make()->title('积分'),
            // 'pay_price'       => ListItem::make()->title('消费金额'),
            // 'study_time'      => ListItem::make()->title('学习时长'),
            'register_device' => ListItem::make()->title('来源'),
            'create_time'     => ListItem::make()->title('注册时间'),
            'last_login_time' => ListItem::make()->title('最近登录时间'),
            'status'          => ListItem::make('custom')->title('状态'),
        ];

        $searchKey = [
            'mhm_id'    => FormItem::make('searchSchool')->title(false)->visible(request()->is_platform),
            'user_name' => FormItem::make()->title(false)->placeholder('用户名')->maxlength(30),
            'phone'     => FormItem::make()->title(false)->placeholder('手机号')->maxlength(30),
            'status'    => FormItem::make('select')->title(false)->placeholder('账号状态')->options([
                ['title' => '不限制', 'value' => -1],
                ['title' => '正常', 'value' => 1],
                ['title' => '禁止', 'value' => 0],
            ]),
        ];

        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey = $keyList;
        // 自定义排序
        // $list->pageKeySort = ['update_time DESC', 'user_name'];
        $list->searchKey     = $searchKey;
        $list->searchKeySort = [];
        $list->datas         = $data;

        return $list->send();
    }

    /**
     * 创建学员
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-15
     *
     * @return Response [type]                         [description]
     */
    public function createUser(): Response
    {
        if (Request::isPost()) {
            $data = Request::post();
            $user = $this->accountLogic->addUser($data);

            return $this->parseToData($user, 1, '创建成功');
        }
        // 定义字段
        $keyList = [
            // 'user_name' => FormItem::make()->title('用户名')->placeholder('请输入用户名')->required(),
            // 'nick_name' => FormItem::make()->title('昵称')->placeholder('请输入昵称'),
            'phone'    => FormItem::make()->title('手机号')->placeholder('请输入手机号')->required(),
            'password' => FormItem::make('inputPassword')->title('登录密码')->placeholder('登录密码')->required(),
            // 'status'   => FormItem::make('slideSwitch')->title('账号状态')->activeValue(1)->inactiveValue(0)->required(),
        ];
        // 设置表单
        $form = new PageForm();
        // 表单字段
        $form->pageKey = $keyList;

        return $form->send();
    }

    /**
     * 编辑学员
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-15
     *
     * @param $id
     * @return Response [type]                         [description]
     */
    public function editUser($id): Response
    {
        if (Request::isPut()) {
            $data = Request::put();
            $user = $this->accountLogic->editUser($data);

            return $this->parseToData($user, 1, '编辑成功');
        }

        $datas = $this->accountLogic->where('id', $id)->findOrFail();

        // 创建课程界面配置
        // 定义字段
        $keyList = [
            // 'user_name' => FormItem::make()->title('用户名')->placeholder('请输入用户名')->required(),
            'nick_name' => FormItem::make()->title('昵称')->placeholder('请输入昵称'),
            'phone'     => FormItem::make()->title('手机号')->placeholder('请输入手机号')->required(),
            'password'  => FormItem::make('inputPassword')->title('登录密码')->placeholder('登录密码')->help('不填写密码不更改'),
            // 'status'    => FormItem::make('slideSwitch')->title('账号状态')->activeValue(1)->inactiveValue(0)->required(),
        ];
        // 设置表单
        $form = new PageForm();
        // 表单字段
        $form->pageKey = $keyList;
        $form->datas   = $datas;

        return $form->send();
    }

    /**
     * 删除后台用户
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-12
     */
    public function deleteUser(int $id): Response
    {
        $this->accountLogic->deleteUser($id);

        return $this->parseToData([], 1, '删除成功');
    }

    /**
     * 更新用户账号状态
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-07
     *
     * @param int $id
     * @return Response [type]                             [description]
     */
    public function updateStatus(int $id): Response
    {
        $status = Request::put('status/d', 1);

        $this->accountLogic->updateStatus($id, $status);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 用户学习概况
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-30
     *
     * @param int $id [description]
     * @return Response [type]                             [description]
     */
    public function study(int $id): Response
    {
        $data = [];
        // 用户信息
        $data['user'] = AccountLogic::with(['avatarUrl', 'balance', 'income', 'credit'])->findOrEmpty($id)->append(['status_text', 'register_device_text']);
        // 用户学习概况
        $data['survey'] = $this->learnRecord->getRecord($id);

        return $this->parseToData($data, 1);
    }

    /**
     * 学习记录分页数据
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-31
     *
     * @param int $id [description]
     * @return Response [type]                             [description]
     */
    public function learnRecord(int $id): Response
    {
        $data = $this->courseStudent->getCourseListByUserId($id);

        return $this->parseToData($data, 1);
    }

    /**
     * 用户购买记录
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-31
     *
     * @param int $id [description]
     * @return Response [type]                             [description]
     */
    public function buyLogs(int $id): Response
    {
        $data = $this->paymentOrderItem->getOrderListByUserId($id);

        return $this->parseToData($data, 1);
    }

    /**
     * 批量禁用
     *
     * @return Response
     */
    public function disables(): Response
    {
        $ids = Request::put('ids/a');
        $this->accountLogic->batchUpdated($ids, 'status', 0);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量启用
     *
     * @return Response
     */
    public function enables(): Response
    {
        $ids = Request::put('ids/a');
        $this->accountLogic->batchUpdated($ids, 'status', 1);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量删除
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @param $ids
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function deletes($ids): Response
    {
        $this->accountLogic->deleteUsers($ids);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 导入学员
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-10
     *
     * @return Response [type]                                    [description]
     */
    public function importStudent(): Response
    {
        $attach_id = Request::post('attach_id/d');
        $res       = $this->accountLogic->doImportStudent($attach_id);

        return $this->parseToData($res, 1, '操作完成');
    }

    /**
     * 搜索
     *
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function search()
    {
        $keyword = Request::get('keyword/s', '');

        $datas = $this->accountLogic->searchStudent($keyword);

        return $this->parseToData($datas, 1);
    }

}
